import { defineStore } from 'pinia'
import { searchGoogleApi } from '@/api/Desktop/Search.js'
const useHeadrSearch = defineStore('useHeadrSearch', {
  state: () => ({
    searchRecordListDom: '',
    recommendList: [],
    isShowSearchHistory: false,
    currentSearchValue: '',
    isFocused: false,
    searchHistoryList: window.localStorage.getItem('searchHistoryList')
      ? JSON.parse(window.localStorage.getItem('searchHistoryList'))
      : [],
    MAX_SEARCH_HISTORY_LENGTH: 10,
    isShowvirtualRecordList: false
  }),
  actions: {
    //用户点击搜索icon进行搜索
    userSearchActions() {
      if(this.currentSearchValue ==''){
        this.currentSearchValue ='JavaScript'
        this.userSaveRecord()
      }  
      else{
      this.userSaveRecord()
      }  
    },
    //用户点击历史记录进行搜索
    userClickRecordActions(txt){
      this.currentSearchValue =txt
      this.userSaveRecord()
    },
    //用户删除一条搜索记录
    userdeleteSearchRecord(index) {
      this.searchHistoryList.splice(index, 1)
      window.localStorage.setItem(
        'searchHistoryList',
        JSON.stringify(this.searchHistoryList)
      )
    },
    //保存用户搜索记录
    userSaveRecord() {
      // 获取本地缓存的搜索记录
      // 检查是否有重复的搜索记录
      const existingIndex = this.searchHistoryList.indexOf(
        this.currentSearchValue
      )
      if (existingIndex > -1) {
        // 如果存在则删除该记录
        this.searchHistoryList.splice(existingIndex, 1)
      }
      // 添加新的搜索记录到开头
      this.searchHistoryList.unshift(this.currentSearchValue)
      // 如果记录超过最大长度，则删除最后一项
      if (this.searchHistoryList.length > this.MAX_SEARCH_HISTORY_LENGTH) {
        this.searchHistoryList.pop()
      }
      // 更新虚拟记录列表使得用户能够实时看到更新效果
      this.searchHistoryList.indexOf(this.currentSearchValue) === -1
        ? this.searchHistoryList.unshift(this.currentSearchValue)
        : ''
      // 更新本地缓存
      window.localStorage.setItem(
        'searchHistoryList',
        JSON.stringify(this.searchHistoryList)
      )
    },
    //搜索
    async searchGoogleApi() {
      const result = await searchGoogleApi(this.currentSearchValue)
      this.recommendList = result
    },
  }
})
export default useHeadrSearch
